from httpUtil import HttpUtil
from DateTimeUtil import DateTimeUtil
http = HttpUtil("http://api1.zelfly.com/carManager/assist/analysis/")
dtu = DateTimeUtil()


def getCarId():
    """
    获取项目车队和车辆信息
    @return: 包含项目车队车辆信息的dict
    """
    try:
        null = ''
        carIdList = []
        result = eval(http.get())
        if result != '':
            if result['code'] == 1:
                product_result = result['result']
                for product_id in product_result:
                    product = product_result[product_id]
                    teamList = product['team']
                    for team in teamList:
                        team_id = team['id']
                        carList = team['car']
                        for car in carList:
                            car_id = car['carId']
                            carIdList.append(car_id)
        return carIdList
    except Exception as e:
        return []

def getCarCoord(path, startTime, endTime):
    """
    获取车辆行驶经纬度信息
    @param path: 请求路径
    @param startTime: 数据开始时间
    @param endTime: 数据终止时间
    @return: 车辆经纬度list
    """
    try:
        false = False
        true = True
        params = {
            "Identifier": 'Longitude-Latitude',
            "StartTime": startTime,
            "PageSize": 10000,
            "Asc": 1,
            "EndTime": endTime
        }
        result = eval(http.get(path=path, params=params))
        if result != '':
            if result['code'] == 1:
                result = result['result']
                if (result['PropertyDataInfos']['PropertyDataInfo']==[]): return []
                LatitudeList = result['PropertyDataInfos']['PropertyDataInfo'][0]['List']['PropertyInfo']
                LongitudeList = result['PropertyDataInfos']['PropertyDataInfo'][1]['List']['PropertyInfo']
                CoordList = []
                for index in range(0, len(LatitudeList)):
                    Coord = {}
                    Coord['Latitude'] = LatitudeList[index]['Value']
                    Coord['Longitude'] = LongitudeList[index]['Value']
                    Coord['time'] = LongitudeList[index]['Time']
                    CoordList.append(Coord)
                    index = index + 1
                if result['NextValid']:
                    startTime = result['NextTime']
                    CoordList = CoordList + getCarCoord(path, startTime, endTime)
                else:
                    pass
                return CoordList
            else:
                return []
        else:
            return []
    except Exception as e:
        return []

def getTimeStamp(date=''):
    """
    根据日期获取前一天的开始时间戳和结束时间戳-s
    @param date: 日期
    @return: 开始时间戳和结束时间戳
    """
    if date == '':
        date = dtu.timeStamp2date()
    beginTime = date + ' 00:00:00'
    beginTimeStamp = dtu.datetime2timeStamp(beginTime) - 86400
    endTime = date + ' 23:59:59'
    endTimeStamp = dtu.datetime2timeStamp(endTime) - 86400
    # print(beginTimeStamp, endTimeStamp)
    return beginTimeStamp, endTimeStamp, date

def saveJson(CoordList, date):
    with open(f'../{date}.json', 'w+') as fp:
        fp.write(CoordList)

if __name__ == '__main__':
    carIdList = getCarId()
    date = ''
    CoordDate = {}
    for carId in carIdList:
        path = f'car/{carId}'
        beginTimeStamp, endTimeStamp, date = getTimeStamp()
        CoordList = getCarCoord(path, beginTimeStamp*1000, endTimeStamp*1000+999)
        CoordDate[f'{carId}'] = CoordList
    saveJson(str(CoordDate).replace("'", '"'), date)